package;

import lib.dbbase.Db;
import lib.http.Http;
import lib.http.Request;
import lib.Fiber.Json;
import lib.Fiber.Console;
import lib.http.Request.Method;

using lib.TypeHelp;


class Main {
	static public function main() {

		var server = new Http(82, function(rst:Request) { // 监听81端口   GET HTTP1.1  user=吴宇彬&password=qqqqqq (  hashMap  ( xxx=xxx  )
			rst.response.addHeader("Access-Control-Allow-Origin", "*"); // 允许跨域
			var map = new Map<String, Dynamic>();
			switch (rst.value) { //
				case "/reg": // 注册
					var userName:String;
					var passWord:String;
					var nick:String;
					if (rst.method == Method.GET) {
						userName = rst.query.userName;
						passWord = rst.query.passWord;
						nick = rst.query.nick;
					} else {
						userName = rst.form.userName;
						passWord = rst.form.passWord;
						nick = rst.form.nick;
					}
					if (userName.length > 0 || passWord.length > 0) {
						var result = Main.mysql.execute("select Id from user where userName=?", userName); // 直接获得查询结果， java 需要从集合拿结果
						trace(result);
						if (result != null && result.length > 0) { // 已注册
							map.set("state", 2);
						} else { // 未注册
							try {
								Main.mysql.execute("insert into user ( userName,passWord,regTime,Nick ) value (?,?,?,?)", userName, passWord, Date.now()
									.getTime(), nick);
							} catch (e:Dynamic) {
								map.set("state", 0);
							}
							login(userName, passWord, map);
						}
					} else {
						map.set("state", 3);
					}
				case "/login":
					if (rst.method == Method.GET) {
						login(rst.query.userName, rst.query.passWord, map);
					} else {
						login(rst.form.userName, rst.form.passWord, map);
					}

				case "/autoLogin":
					if (rst.method == Method.GET) {
						autoLogin(rst.query.cookies, map);
					} else {
						autoLogin(rst.form.cookies, map);
					}

				default:
			}
			untyped rst.response.write(Json.stringify((Reflect.getProperty(map, "h"))));
		});
		trace("服务端启动 82端口");
		server.run();
	} /**
	 * 登录
	 * @param userName 账号
	 * @param passWord 密码
	 */

	public static function login(userName:String, passWord:String, ?map:Map<String, Dynamic>) {
		// var obj = haxe.Json.parse(jsonData);
		var rs = Main.mysql
			.execute("select Id,userName,regTime,Nick from user where userName=? and passWord=? ", userName, passWord); // 直接获得查询结果， java 需要从集合拿结果
		if (rs != null && rs.length > 0) { // 已注册
			map.set("state", 1);
			map.set("data", rs[0]);
			var _cookies = randomStr();
			Main.cookies.set(_cookies, rs[0].Id); // 内存记录 cookies [  cookies  ] => [ 用户id ];
			map.set("cookies", _cookies); // 发给客户端
		} else {
			map.set("state", 0);
		}
	}

	/**
	 * 生成16位随机文本  
	 */
	public static function randomStr(len:Int = 16):String {
		var tab = [for (i in "A".code..."z".code) String.fromCharCode(i)];
		return [for (i in 0...len) tab[(Math.random() * tab.length).toInt()]].join("");
	}

	public static function autoLogin(cookies:String, ?map:Map<String, Dynamic>) {
		trace(cookies);
		var id = Main.cookies.get(cookies);
		if (id != null) { // 根据cookies 拿 id
			var rs = Main.mysql.execute("select Id,userName,regTime,Nick from user where Id=? ", id);
			map.set("state", 1);
			map.set("data", rs[0]);
			var _cookies = randomStr(); // 更新cookies
			Main.cookies.remove(cookies); // 删除原来的cookies
			Main.cookies.set(_cookies, rs[0].Id); // 内存记录 cookies [  cookies  ] => [ 用户id ];
			map.set("cookies", _cookies); // 发给客户端
		} else { // 自动登录失败 。
			map.set("state", 0);
		}
	};

	public static var cookies = new Map<String, Int>();
	public static var mysql = Db.openMySQL("mysql://root:root@127.0.0.1/userlogin"); // 翻译
}
